package roles;

import avenue.MyWindowEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.DBManager;
import model.Module;
import model.RolePermission;
import model.UserRole;
import utils.Utils;

public class EditRoleForm extends javax.swing.JFrame {

    public EditRoleForm() {
        em = DBManager.em;
        newRolePermissions = new ArrayList<RolePermission>();
        initComponents();
    }
    
     public EditRoleForm(UserRole ur, boolean readOnly) {
        em = DBManager.em;
        newRolePermissions = new ArrayList<RolePermission>();
        userRole1=ur;
        this.readOnly = readOnly;
        initComponents();
    }
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        userRole2 = userRole1;
        rolePermissionQuery = em.createQuery("select rp from RolePermission rp where rp.roleId=:userRole").setParameter("userRole",userRole2);
        rolePermissionList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(rolePermissionQuery.getResultList());
        roleBoxRenderer1 = new avenue.RoleBoxRenderer();
        roleNameLabel = new javax.swing.JLabel();
        separator = new javax.swing.JSeparator();
        roleNameTF = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        rolePermissionScrollPane = new javax.swing.JScrollPane();
        rolePermissionTable = new javax.swing.JTable();
        newRolePermissionButton = new javax.swing.JButton();
        deleteRolePermissionButton = new javax.swing.JButton();
        editRolePermissionButton = new javax.swing.JButton();

        roleBoxRenderer1.setText("roleBoxRenderer1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Επεξεργασία Ρόλου");

        roleNameLabel.setText("Όνομα Ρόλου : ");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, userRole2, org.jdesktop.beansbinding.ELProperty.create("${roleName}"), roleNameTF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/save.gif"))); // NOI18N
        saveButton.setText("Αποθήκευση");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        cancelButton.setText("Ακυρο");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, rolePermissionList, rolePermissionTable, "rolePermissionList");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${moduleId}"));
        columnBinding.setColumnName("Module Id");
        columnBinding.setColumnClass(model.Module.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stationLevelAccess}"));
        columnBinding.setColumnName("Station Level Access");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canCreate}"));
        columnBinding.setColumnName("Can Create");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canRetrieve}"));
        columnBinding.setColumnName("Can Retrieve");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canUpdate}"));
        columnBinding.setColumnName("Can Update");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${canDelete}"));
        columnBinding.setColumnName("Can Delete");
        columnBinding.setColumnClass(Boolean.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();

        rolePermissionScrollPane.setViewportView(rolePermissionTable);

        newRolePermissionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        newRolePermissionButton.setText("Νέο");
        newRolePermissionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newRolePermissionButtonActionPerformed(evt);
            }
        });

        deleteRolePermissionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        deleteRolePermissionButton.setText("Διαγραφή");
        deleteRolePermissionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteRolePermissionButtonActionPerformed(evt);
            }
        });

        editRolePermissionButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit1.png"))); // NOI18N
        editRolePermissionButton.setText("Επεξεργασία");
        editRolePermissionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editRolePermissionButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(rolePermissionScrollPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 816, Short.MAX_VALUE)
                    .addComponent(separator, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(roleNameLabel)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(roleNameTF))
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(cancelButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(saveButton)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(newRolePermissionButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(deleteRolePermissionButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(editRolePermissionButton)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(roleNameLabel)
                    .addComponent(roleNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(separator, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rolePermissionScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(newRolePermissionButton)
                    .addComponent(deleteRolePermissionButton)
                    .addComponent(editRolePermissionButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed

        // Διαγραφή των νέων δικαιωμάτων
        for (RolePermission rp : newRolePermissions) { 
             em.remove(rp);
        }
        
        // Διαχείριση παραθύρων
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,false);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false); 
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        // Διαχείριση παραθύρων
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED,true);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false); 
    }//GEN-LAST:event_saveButtonActionPerformed
    
    private void moduleSelection() { 
        
        selectedModule = null;
        RoleSelectionForm msf = new RoleSelectionForm(mList);
        msf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        
        //************
        msf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
               System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){
                   selectedModule = mList.get(0);
                   // Δημιούργησε ένα νέο δικαίωμα
                   rp = new RolePermission();
                   // Κάνε managed to νέο δικαίωμα
                   em.persist(rp);
                   // Θέσε τις πληροφορίες του
                   rp.setModuleId(selectedModule);
                   rp.setRoleId(userRole2);
                   rp.setStationLevelAccess(true);
                   rp.setCanCreate(true);
                   rp.setCanRetrieve(true);
                   rp.setCanUpdate(true);
                   rp.setCanDelete(true);
                   // Πρόσθεσέ το στην λίστα
                   rolePermissionList.add(rp);
                   // Εμφάνισέ το στον πίνακα
                   Utils.updateJTable(rolePermissionTable, bindingGroup, "rolePermissionList");
                   // Κάνε την νέα εγγραφή selected
                   int row = rolePermissionList.size()-1;
                   rolePermissionTable.setRowSelectionInterval(row, row);
                   // Κάλεσε την μέθοδο editRolePermissionButtonActionPerformed
                   newRolePermission = true;
                   editRolePermissionButtonActionPerformed(null);
               }
               thisFrame.setEnabled(true);
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        
    }
    
    private void newRolePermissionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newRolePermissionButtonActionPerformed

        // Έλεγχος για το αν υπάρχουν modules για τα οποία δεν έχει οριστεί κάποιο δικαίωμα
        Query q = em.createQuery("select m from Module m");
        // Πάρε την λίστα με όλα τα modules
        try { 
            mList = new ArrayList(q.getResultList());
        } catch(NoResultException ex) { 
            JOptionPane.showMessageDialog(this, "Μη δυνατή η ανάκτηση των modules!.",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        }
        // Αφαίρεσε από την λίστα αυτή τα modules για τα οποία έχουν
        // οριστεί δικαιώματα
        for (int i = mList.size()-1; i >= 0; i--) { 
             Module m = mList.get(i);
             for (RolePermission rp : rolePermissionList) { 
                  if (rp.getModuleId().getId().toString().equals(m.getId().toString())) { 
                      mList.remove(m);
                      break;
                  }
             }
        }
        // Έλεγχος του μεγέθους της λίστας
        if (mList.size() == 0) { 
            JOptionPane.showMessageDialog(this, "Έχει οριστεί δικαίωμα για όλα τα modules!.",
                                          "Σφάλμα",JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // Επέλεξε το module για το οποίο θα πρέπει να οριστεί ένα νέο δικαίωμα
        moduleSelection();
     
    }//GEN-LAST:event_newRolePermissionButtonActionPerformed

    private void editRolePermissionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editRolePermissionButtonActionPerformed

        s = rolePermissionTable.getSelectedRow();
        
        if (s >= 0) {
            rp = rolePermissionList.get(rolePermissionTable.convertRowIndexToModel(s));
            RolePermissionDialogueForm rpf = new RolePermissionDialogueForm(rp);
            
            rpf.setVisible(true);
            thisFrame = this;
            thisFrame.setEnabled(false);
        
       
       //************
        System.out.println("newRolePermission: " + newRolePermission);
        rpf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
               if (((MyWindowEvent)arg0).exitAndSave){

                    newRolePermissions.add(rp);
                    
                    rolePermissionTable.setRowSelectionInterval(s, s);
                    rolePermissionTable.scrollRectToVisible(rolePermissionTable.getCellRect(s, 0, true));
                    thisFrame.setEnabled(true);
                } else{
                    thisFrame.setEnabled(true);
                    if (newRolePermission) {
                        rolePermissionList.remove(rp);
                        em.remove(rp);
                    } else {
                        em.refresh(rp);
                    }
                }
                Utils.updateJTable(rolePermissionTable, bindingGroup, "rolePermissionList");
                newRolePermission = false;
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Window Activated");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });
        }
    }//GEN-LAST:event_editRolePermissionButtonActionPerformed

    private void deleteRolePermissionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteRolePermissionButtonActionPerformed
        
        int s = rolePermissionTable.getSelectedRow();
        if (s >= 0) {
            RolePermission pr = rolePermissionList.get(rolePermissionTable.convertRowIndexToModel(s));
            // Επιβεβαίωση της διαγραφής
            int choice = JOptionPane.showConfirmDialog(this,
                                      "Διαγραφή του συγκεκριμένου δικαιώματος;",
                                      "Επιβεβαίωση διαγραφής δικαιώματος",
                                      JOptionPane.YES_NO_OPTION);
                
            if (choice != 0)
                return;
            
            em.remove(pr);
            rolePermissionList.remove(pr);
            utils.Utils.updateJTable(rolePermissionTable, bindingGroup, "rolePermissionList");
        }
        
    }//GEN-LAST:event_deleteRolePermissionButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton deleteRolePermissionButton;
    private javax.swing.JButton editRolePermissionButton;
    private javax.swing.JButton newRolePermissionButton;
    private avenue.RoleBoxRenderer roleBoxRenderer1;
    private javax.swing.JLabel roleNameLabel;
    private javax.swing.JTextField roleNameTF;
    private java.util.List<RolePermission> rolePermissionList;
    private javax.persistence.Query rolePermissionQuery;
    private javax.swing.JScrollPane rolePermissionScrollPane;
    private javax.swing.JTable rolePermissionTable;
    private javax.swing.JButton saveButton;
    private javax.swing.JSeparator separator;
    private model.UserRole userRole2;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    EntityManager em;
    UserRole userRole1;
    private int s;
    private RolePermission rp;
    private JFrame thisFrame;
    private boolean readOnly;
    private Module selectedModule;
    private ArrayList<Module> mList;
    private boolean newRolePermission = false;
    private ArrayList<RolePermission> newRolePermissions;
    
}
